<script setup>
import {onMounted, ref} from "vue";
import GetMap from "src/utils/GetMap.js";
import {QUERY_CONTROL} from "src/constant/data.js";
import {getBuildInfo,deleteBuildInfo,updateBuildInfo} from "src/utils/GetBuildInfo.js";
import Result from "components/query/Result.vue";
import { ElMessage } from 'element-plus'
import {useQueryStore} from "stores/query.js";

let map;
let buildLayer;
let drawLayer;
let dialog = ref(false);
let tableData = ref([]);
const queryStore = useQueryStore();

onMounted(() => {
  map = GetMap(QUERY_CONTROL);
  queryStore.map = map;
  buildLayer = L.geoJSON().addTo(map);
  drawLayer = L.featureGroup().addTo(map);
  map.on("pm:create", async (e) => {
    drawLayer.clearLayers();
    buildLayer.clearLayers();
    tableData.value = [];
    let layer = e.layer;
    drawLayer.addLayer(layer);
    let geojson = layer.toGeoJSON()
    let result = await getBuildInfo(geojson);
    if (result.status !== 200) {
      // TODO: 对话框提示错误信息
      ElMessage.error('查询失败,请重新绘制');
      return;
    }
    else {
      // TODO: 对话框提示成功信息
      ElMessage.success('查询成功');
      let buildInfo = result.data.data;
      buildLayer.clearLayers();
      buildLayer.addData(buildInfo);
      buildLayer.eachLayer(function (layer) {
        layer.bindPopup(layer.feature.properties.name);
        layer.on('contextmenu', function (event) {
          let id=event.target.feature.properties.id
          const createButton = (text, bgColor, onClick) => {
            const button = document.createElement('button');
            button.style.backgroundColor = bgColor;
            button.style.color = 'white';
            button.textContent = text;
            button.style.width = '100px';
            button.style.height = '40px';
            button.style.marginTop = '10px';
            button.style.borderRadius = '20px';
            button.onclick = onClick;
            return button;
          };
          const popupContent = document.createElement('div');
          popupContent.style.width = '100px';
          popupContent.style.height = '150px';
          const deleteButton = createButton('删除', 'red', async () => {
            buildLayer.removeLayer(layer);
            tableData.value = tableData.value.filter(item => item.name !== layer.feature.properties.name);
            map.closePopup();
            let result = await deleteBuildInfo(id);
            if (result.status!== 200) {
              // TODO: 对话框提示错误信息
              ElMessage.error('删除失败');
              return;
            }
             ElMessage.success('删除成功');
          });
          const editButton = createButton('编辑', 'blue', async () => {
            // TODO: 编辑功能
            let name = prompt('请输入名称', layer.feature.properties.name);
            if (name) {
              layer.feature.properties.name = name;
              layer.bindPopup(name);
              let result = await updateBuildInfo(id, {'name': name});
              if (result.status !== 200) {
                // TODO: 对话框提示错误信息
                ElMessage.error('编辑失败');
                return;
              }
              ElMessage.success('编辑成功');
              // 刷新表格数据
              tableData.value = tableData.value.map(item => {
                if (item.id === layer.feature.properties.id) {
                  item.name = name;
                }
                return item;
              });
              map.closePopup();

            } else {
              ElMessage.error('名称不能为空');
            }
          });
          popupContent.appendChild(deleteButton);
          popupContent.appendChild(editButton);
          L.popup()
            .setLatLng(event.latlng)
            .setContent(popupContent)
            .openOn(map);


        });
      });
      let features = buildInfo.features;
      features.forEach(feature => {
        tableData.value.push(
          {
            'id': feature.properties.id,
            'name': feature.properties.name,
            'lat': feature.geometry.coordinates[1],
            'lng': feature.geometry.coordinates[0],
          }
        );
      });
      dialog.value = true;
    }

  });
})
const resetSize = () => {
  map.setView( [34.83160, 113.54436], 16.7 );
}
</script>

<template>
<div id="map">
  <q-btn color="primary" class="query" @click="dialog = true">
    结果显示
  </q-btn>
  <q-btn color="deep-orange" class="query1" @click="resetSize">
    恢复大小
  </q-btn>

</div>
  <Result v-model:dialog="dialog" v-model:tableData="tableData"></Result>
</template>

<style scoped>
.query {
  max-width: 100px;
  width: 10%;
  position: absolute;
  top: 20px;
  right: 10px;
  z-index: 1002;
}
.query1 {
  max-width: 100px;
  width: 10%;
  position: absolute;
  top: 70px;
  right: 10px;
  z-index: 1002;
}
</style>
